package com.foodie.servlet;

import com.foodie.entity.User;
import com.foodie.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String acc = req.getParameter("user_id");
        String pwd = req.getParameter("user_pwd");
        User user = userService.login(acc, pwd);
        if (user != null) {
            String token = UUID.randomUUID().toString();
            userService.setToken(token, user.getId());
            Cookie cookie = new Cookie("token", token);
            cookie.setMaxAge(3600 * 24 * 30);
            cookie.setPath("/");
            resp.addCookie(cookie);
            req.getSession().setAttribute("user", user);
            req.getSession().setAttribute("msg", "登陆成功");
            resp.sendRedirect(req.getContextPath() + "/ces.jsp");
        } else {
            req.getSession().setAttribute("msg", "账号或密码错误！");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }
    }
}
